//
//  EmoticonTextView.swift
//  EmoticonKeyBoard
//
//  Created by yang on 15/11/22.
//  Copyright © 2015年 yang. All rights reserved.
//

import UIKit

class EmoticonTextView: UITextView {
    //将属性文本转换成字符串
    func fulltext() -> String
    {
        let attText = attributedText
        var strM = String()
        //遍历属性文本的属性
        attText.enumerateAttributesInRange(NSRange(location: 0, length: attText.length), options: []) { (dict, range , _) -> Void in
            if let attachment = dict["NSAttachment"] as? EmoticonAttachment {
            let text = attachment.chs
                strM += (text ?? "")
            }else{
            let str = (attText.string as NSString).substringWithRange(range)
                strM += str
            }
        }
        return strM
    }
    func insertAttrText(emoticon:Emoticon){
        if emoticon.isEmpty {
            print("空表情")
            return
        }
        if emoticon.isRemove {
            deleteBackward()
            return
        }
        if emoticon.code != nil {
            replaceRange(selectedTextRange!, withText: emoticon.emojiString ?? "")
            return 
        }
        //将点击的图片添加到 附件中
        let imageText = EmoticonAttachment().emoticonimageText(emoticon,font:font!)
        let range = selectedRange
        
        let text = NSMutableAttributedString(attributedString:attributedText)
        text.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
        attributedText = text
        selectedRange = NSMakeRange(range.location + 1, 0)
    }
}
